package logic

import (
	"context"
	"strconv"
	"taobao/api/pkg"
	"taobao/goods_srv/user"

	"taobao/api/internal/svc"
	"taobao/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MobileLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMobileLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MobileLoginLogic {
	return &MobileLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MobileLoginLogic) MobileLogin(req *types.MobileSmsCodeRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 手机号登录
	//查询用户信息
	mobile, err := l.svcCtx.UserSrv.UserLoginByMobile(l.ctx, &user.UserLoginByMobileRequest{Mobile: req.Mobile})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "用户信息获取失败",
			Data: nil,
		}, err
	}

	if !(req.Code == mobile.Code) {
		return &types.RegMsgResponse{
			Cre:  -2,
			Mag:  "验证码错误",
			Data: nil,
		}, err
	}

	_, err = l.svcCtx.UserSrv.UserLoginByMobile(l.ctx, &user.UserLoginByMobileRequest{
		Mobile: req.Mobile,
		Code:   req.Code,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -3,
			Mag:  "服务器错误",
			Data: nil,
		}, err
	}

	token, err := pkg.GetJwtToken(strconv.FormatInt(mobile.UserId, 10))
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -4,
			Mag:  "token生成失败",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Cre: -3,
		Mag: "登录成功",
		Data: map[string]interface{}{
			"token": token,
		},
	}, err
}
